/**
* 判断此对象是否是Object类型
* @param {Object} obj
*/
export const isObject = (obj) => {
  return Object.prototype.toString.call(obj) === '[object Object]';
};
/**
* 判断此类型是否是Array类型
* @param {Array} arr
*/
export const isArray = (arr) => {
  return Object.prototype.toString.call(arr) === '[object Array]';
};
/**
*  深度比较两个对象是否相同
* @param {Object} oldData
* @param {Object} newData
*/
export const equalsObj = (oldData, newData) => {
  // 类型为基本类型时,如果相同,则返回true
  if (oldData === newData) return true;
  if (isObject(oldData) && isObject(newData) && Object.keys(oldData).length === Object.keys(newData).length) {
    // 类型为对象并且元素个数相同

    // 遍历所有对象中所有属性,判断元素是否相同
    for (const key in oldData) {
      if (oldData.hasOwnProperty(key)) {
        if (!equalsObj(oldData[key], newData[key]))
          // 对象中具有不相同属性 返回false
          return false;
      }
    }
  } else if (isArray(oldData) && isArray(oldData) && oldData.length === newData.length) {
    // 类型为数组并且数组长度相同

    for (let i = 0, length = oldData.length; i < length; i++) {
      if (!equalsObj(oldData[i], newData[i]))
        // 如果数组元素中具有不相同元素,返回false
        return false;
    }
  } else {
    // 其它类型,均返回false
    return false;
  }

  // 走到这里,说明数组或者对象中所有元素都相同,返回true
  return true;
};


export const dateFormat = function (fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
    };
  };
  return fmt;
};

export const getLocationMsg = (state) => {
  return new Promise(function (resolve, reject) {
    wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: async (res) => {
        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
        var speed = res.speed; // 速度，以米/每秒计
        var accuracy = res.accuracy; // 位置精度
        // const _search = `/v1/?key=${configOut.tencentMapKey}&location=${latitude},${longitude}`
        // console.log("resMd5", md5(_search));
        // state.locationMsg = await axios.get(`https://apis.map.qq.com/ws/geocoder${_search}&sig=${md5(_search)}`)
        // console.log("state.locationMsg", state.locationMsg);
        let resLocation = await Vue.axios.get(`/api/getLocation/${latitude},${longitude}`);
        console.log("位置信息", res, resLocation);
        resolve(resLocation);
      }
    });
  });
};


export const base64ToBlob = (urlData, type) => {
  let arr = urlData.split(',');
  let mime = arr[0].match(/:(.*?);/)[1] || type;
  // 去掉url的头，并转化为byte
  let bytes = window.atob(arr[1]);
  // 处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length);
  // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
  let ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], {
    type: mime
  });
};


// jssdk获取图片base64信息(变异步为同步)
export const promise = (localId) => {
  return new Promise(function (resolve, reject) {
    wx.getLocalImgData({
      localId: localId.toString(),
      success: function (res) {
        var localData = res.localData;
        if (localData.indexOf('data:image') != 0) {
          //判断是否有这样的头部
          localData = 'data:image/jpeg;base64,' + localData;
        }
        localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg'); // 此处的localData 就是你所需要的base64位
        resolve(localData);
      }
    });
  });
};


// base64转file
export const dataURLtoFile = (dataurl, filename = `${Date.now().jpeg}`) => {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  const blob = new Blob([u8arr], { type: mime });
  return new File([blob], filename, { type: mime, lastModified: Date.now() });
};


// 判断平台
export const getPlatform = () => {
  let p = navigator.platform;
  let u = navigator.userAgent;
  let is_android = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
  let is_ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (p == "Win32" || p == "Win64" || p == "MacPPC" || p == "MacIntel" || p == "X11" || p == "Linux i686") {//PC调试环境
    return "Pc";
  }
  else {
    if (is_android) {//Android终端
      return "Android";
    }
    else if (is_ios) {//IOS终端
      return "IOS";
    }
  }
};

//防抖  一定时间内只会执行最后一次
export const debounce = (func, wait = 0) => {
  if (typeof func !== 'function') {
    throw new TypeError('need a function arguments');
  }
  let timeid = null;
  let result;

  return function () {
    let context = this;
    let args = arguments;

    if (timeid) {
      clearTimeout(timeid);
    }
    timeid = setTimeout(function () {
      result = func.apply(context, args);
    }, wait);

    return result;
  };
};
//节流  一定时间内只会执行一次
export const throttle = (callback, duration) => {
  var lastTime = new Date().getTime();
  return function () {
    var now = new Date().getTime();
    if (now - lastTime > 500) {
      callback();
      lastTime = now;
    }
  };
};

// 判断是否是数字....
export const isNumber = (val) => {
  if (parseFloat(val).toString() == "NaN") {
    return false;
  } else {
    return true;
  }
};

export const isInteger = (obj) => {
  return typeof obj === 'number' && obj % 1 === 0
}

export const controlNumber = (val, len = null) => {
  if (isNumber(val)) {
    if (isInteger(val) || val == 0) {//判断是否是整数
      return val;
    } else {
      const dotBefore = String(val).split('.')[0];//整数部分
      const dotAfter = String(val).split('.')[1];//小数部分
      if (dotBefore.length < 2) {
        if (dotAfter && (dotAfter.length >= 4)) {
          return Number(val).toFixed(len ?? 4);
        } else {
          return Number(val);
        }
      } else {
        return Number(val).toFixed(len ?? 2)
      }
    }
  } else {
    return '--'
  }
}

export const getInstTypeText = {
  SPOT: '现货',
  MARGIN: '币币杠杆',
  SWAP: '永续合约',
  FUTURES: '交割合约',
  OPTION: '期权',
}

export const getOrdType = {
  conditional: '单向止盈止损',
  oco: '双向止盈止损',
  trigger: '计划委托',
  move_order_stop: '移动止盈止损',
  iceberg: '冰山委托',
  twap: '时间加权委托',
}

export const copyToClipboard = (text) => {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}

export const getUrlParam = (name) => {
  const url = window.location.href;
  const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
  const results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}